/**
 * 公告管理API接口
 * 严格按照 APIDOCS/ANNOUNCEMENT-MANAGEMENT-API.md 文档实现
 */

import { http } from "@/utils/http";

// ==================== 类型定义 ====================

/** 通用API响应格式 */
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}

/** 分页响应格式 */
export interface PageResponse<T> {
  records: T[];
  total: number;
  current: number;
  size: number;
  pages: number;
}

/** 公告信息 */
export interface AnnouncementInfo {
  /** 公告ID */
  id: number;
  /** 公告标题 */
  title: string;
  /** 公告内容 */
  content: string;
  /** 公告类型 */
  type: number;
  /** 公告类型名称 */
  typeName: string;
  /** 公告级别 */
  level: number;
  /** 公告级别名称 */
  levelName: string;
  /** 公告状态 */
  status: number;
  /** 公告状态名称 */
  statusName: string;
  /** 是否置顶 */
  isTop: number;
  /** 是否弹窗 */
  isPopup: number;
  /** 目标受众 */
  targetAudience: string;
  /** 目标受众名称 */
  targetAudienceName: string;
  /** 发布时间 */
  publishTime: string;
  /** 过期时间 */
  expireTime: string;
  /** 浏览次数 */
  viewCount: number;
  /** 创建者名称 */
  creatorName: string;
  /** 创建时间 */
  createTime: string;
  /** 更新时间 */
  updateTime: string;
  /** 是否已过期 */
  expired: boolean;
  /** 是否已读 */
  read: boolean;
  /** 剩余天数 */
  remainingDays: number;
}

/** 公告列表查询参数 */
export interface AnnouncementListQuery {
  /** 页码 */
  current?: number;
  /** 每页大小 */
  size?: number;
  /** 公告标题 */
  title?: string;
  /** 公告类型 */
  type?: number;
  /** 公告级别 */
  level?: number;
  /** 公告状态 */
  status?: number;
  /** 是否只查询置顶公告 */
  onlyTop?: boolean;
  /** 排序字段 */
  sortField?: string;
  /** 排序方式 */
  sortOrder?: string;
}

/** 创建公告请求参数 */
export interface CreateAnnouncementRequest {
  /** 公告标题 */
  title: string;
  /** 公告内容 */
  content: string;
  /** 公告类型 */
  type: number;
  /** 公告级别 */
  level: number;
  /** 公告状态 */
  status: number;
  /** 是否置顶 */
  isTop: number;
  /** 是否弹窗 */
  isPopup: number;
  /** 目标受众 */
  targetAudience: string;
  /** 发布时间 */
  publishTime: string;
  /** 过期时间 */
  expireTime: string;
}

/** 更新公告请求参数 */
export interface UpdateAnnouncementRequest extends CreateAnnouncementRequest {
  /** 公告ID */
  id: number;
}

/** 批量操作请求参数 */
export interface BatchOperationRequest {
  /** 公告ID列表 */
  announcementIds: number[];
  /** 操作类型 */
  operation: string;
  /** 操作原因 */
  reason?: string;
}

/** 公告统计信息 */
export interface AnnouncementStatistics {
  /** 总数量 */
  total_count: number;
  /** 草稿数量 */
  draft_count: number;
  /** 已发布数量 */
  published_count: number;
  /** 已过期数量 */
  expired_count: number;
  /** 已删除数量 */
  deleted_count: number;
  /** 置顶数量 */
  top_count: number;
  /** 弹窗数量 */
  popup_count: number;
  /** 总浏览次数 */
  total_view_count: number;
}

// ==================== 枚举定义 ====================

/** 公告类型 */
export enum AnnouncementType {
  /** 系统公告 */
  SYSTEM = 1,
  /** 活动公告 */
  ACTIVITY = 2,
  /** 维护公告 */
  MAINTENANCE = 3,
  /** 其他 */
  OTHER = 4
}

/** 公告级别 */
export enum AnnouncementLevel {
  /** 普通 */
  NORMAL = 1,
  /** 重要 */
  IMPORTANT = 2,
  /** 紧急 */
  URGENT = 3
}

/** 公告状态 */
export enum AnnouncementStatus {
  /** 草稿 */
  DRAFT = 0,
  /** 已发布 */
  PUBLISHED = 1,
  /** 已过期 */
  EXPIRED = 2,
  /** 已删除 */
  DELETED = 3
}

/** 目标受众 */
export enum TargetAudience {
  /** 所有用户 */
  ALL = "all",
  /** 管理员 */
  ADMIN = "admin",
  /** 普通用户 */
  USER = "user"
}

/** 批量操作类型 */
export enum BatchOperationType {
  /** 发布 */
  PUBLISH = "publish",
  /** 存档 */
  ARCHIVE = "archive",
  /** 删除 */
  DELETE = "delete",
  /** 置顶 */
  TOP = "top",
  /** 取消置顶 */
  UNTOP = "untop",
  /** 设为弹窗 */
  POPUP = "popup",
  /** 取消弹窗 */
  UNPOPUP = "unpopup"
}

// ==================== 管理员接口 ====================

/** 分页查询公告列表（管理员） */
export const getAdminAnnouncementListApi = (params: AnnouncementListQuery) => {
  return http.request<ApiResponse<PageResponse<AnnouncementInfo>>>(
    "get",
    "/admin/announcements/list",
    { params }
  );
};

/** 创建公告 */
export const createAnnouncementApi = (data: CreateAnnouncementRequest) => {
  return http.request<ApiResponse>("post", "/admin/announcements/create", {
    data
  });
};

/** 更新公告 */
export const updateAnnouncementApi = (data: UpdateAnnouncementRequest) => {
  return http.request<ApiResponse>("put", `/admin/announcements/${data.id}`, {
    data
  });
};

/** 删除公告 */
export const deleteAnnouncementApi = (announcementId: number) => {
  return http.request<ApiResponse>(
    "delete",
    `/admin/announcements/${announcementId}`
  );
};

/** 批量操作公告 */
export const batchOperateAnnouncementsApi = (data: BatchOperationRequest) => {
  return http.request<ApiResponse>("post", "/admin/announcements/batch", {
    data
  });
};

/** 发布公告 */
export const publishAnnouncementApi = (announcementId: number) => {
  return http.request<ApiResponse>(
    "post",
    `/admin/announcements/${announcementId}/publish`
  );
};

/** 存档公告 */
export const archiveAnnouncementApi = (announcementId: number) => {
  return http.request<ApiResponse>(
    "post",
    `/admin/announcements/${announcementId}/archive`
  );
};

/** 置顶/取消置顶公告 */
export const toggleTopAnnouncementApi = (
  announcementId: number,
  isTop: boolean
) => {
  return http.request<ApiResponse>(
    "post",
    `/admin/announcements/${announcementId}/top`,
    { params: { isTop } }
  );
};

/** 设置/取消弹窗公告 */
export const togglePopupAnnouncementApi = (
  announcementId: number,
  isPopup: boolean
) => {
  return http.request<ApiResponse>(
    "post",
    `/admin/announcements/${announcementId}/popup`,
    { params: { isPopup } }
  );
};

/** 获取公告统计信息 */
export const getAnnouncementStatisticsApi = () => {
  return http.request<ApiResponse<AnnouncementStatistics>>(
    "get",
    "/admin/announcements/statistics"
  );
};

/** 自动过期公告 */
export const autoExpireAnnouncementsApi = () => {
  return http.request<ApiResponse>("post", "/admin/announcements/auto-expire");
};

/** 清理已删除的公告 */
export const cleanDeletedAnnouncementsApi = (daysBeforeClean: number = 30) => {
  return http.request<ApiResponse>(
    "post",
    "/admin/announcements/clean-deleted",
    { params: { daysBeforeClean } }
  );
};

/** 清理过期的阅读记录 */
export const cleanReadRecordsApi = (daysBeforeClean: number = 90) => {
  return http.request<ApiResponse>(
    "post",
    "/admin/announcements/clean-read-records",
    { params: { daysBeforeClean } }
  );
};

// ==================== 工具类 ====================

export class AnnouncementManagementUtils {
  /** 获取公告类型文本 */
  static getTypeText(type: number): string {
    const typeMap = {
      [AnnouncementType.SYSTEM]: "系统公告",
      [AnnouncementType.ACTIVITY]: "活动公告",
      [AnnouncementType.MAINTENANCE]: "维护公告",
      [AnnouncementType.OTHER]: "其他"
    };
    return typeMap[type] || "未知";
  }

  /** 获取公告级别文本 */
  static getLevelText(level: number): string {
    const levelMap = {
      [AnnouncementLevel.NORMAL]: "普通",
      [AnnouncementLevel.IMPORTANT]: "重要",
      [AnnouncementLevel.URGENT]: "紧急"
    };
    return levelMap[level] || "未知";
  }

  /** 获取公告状态文本 */
  static getStatusText(status: number): string {
    const statusMap = {
      [AnnouncementStatus.DRAFT]: "草稿",
      [AnnouncementStatus.PUBLISHED]: "已发布",
      [AnnouncementStatus.EXPIRED]: "已过期",
      [AnnouncementStatus.DELETED]: "已删除"
    };
    return statusMap[status] || "未知";
  }

  /** 获取目标受众文本 */
  static getTargetAudienceText(targetAudience: string): string {
    const audienceMap = {
      [TargetAudience.ALL]: "所有用户",
      [TargetAudience.ADMIN]: "管理员",
      [TargetAudience.USER]: "普通用户"
    };
    return audienceMap[targetAudience] || "未知";
  }

  /** 获取类型标签类型 */
  static getTypeTagType(type: number): string {
    const tagMap = {
      [AnnouncementType.SYSTEM]: "primary",
      [AnnouncementType.ACTIVITY]: "success",
      [AnnouncementType.MAINTENANCE]: "warning",
      [AnnouncementType.OTHER]: "info"
    };
    return tagMap[type] || "info";
  }

  /** 获取级别标签类型 */
  static getLevelTagType(level: number): string {
    const tagMap = {
      [AnnouncementLevel.NORMAL]: "info",
      [AnnouncementLevel.IMPORTANT]: "warning",
      [AnnouncementLevel.URGENT]: "danger"
    };
    return tagMap[level] || "info";
  }

  /** 获取状态标签类型 */
  static getStatusTagType(status: number): string {
    const tagMap = {
      [AnnouncementStatus.DRAFT]: "info",
      [AnnouncementStatus.PUBLISHED]: "success",
      [AnnouncementStatus.EXPIRED]: "warning",
      [AnnouncementStatus.DELETED]: "danger"
    };
    return tagMap[status] || "info";
  }

  /** 格式化浏览次数 */
  static formatViewCount(count: number): string {
    if (count >= 10000) {
      return `${(count / 10000).toFixed(1)}万`;
    }
    return count.toString();
  }

  /** 格式化剩余天数 */
  static formatRemainingDays(days: number): string {
    if (days < 0) return "已过期";
    if (days === 0) return "今天过期";
    if (days === 1) return "明天过期";
    return `${days}天后过期`;
  }

  /** 获取公告类型选项 */
  static getTypeOptions() {
    return [
      { label: "系统公告", value: AnnouncementType.SYSTEM },
      { label: "活动公告", value: AnnouncementType.ACTIVITY },
      { label: "维护公告", value: AnnouncementType.MAINTENANCE },
      { label: "其他", value: AnnouncementType.OTHER }
    ];
  }

  /** 获取公告级别选项 */
  static getLevelOptions() {
    return [
      { label: "普通", value: AnnouncementLevel.NORMAL },
      { label: "重要", value: AnnouncementLevel.IMPORTANT },
      { label: "紧急", value: AnnouncementLevel.URGENT }
    ];
  }

  /** 获取公告状态选项 */
  static getStatusOptions() {
    return [
      { label: "草稿", value: AnnouncementStatus.DRAFT },
      { label: "已发布", value: AnnouncementStatus.PUBLISHED },
      { label: "已过期", value: AnnouncementStatus.EXPIRED },
      { label: "已删除", value: AnnouncementStatus.DELETED }
    ];
  }

  /** 获取目标受众选项 */
  static getTargetAudienceOptions() {
    return [
      { label: "所有用户", value: TargetAudience.ALL },
      { label: "管理员", value: TargetAudience.ADMIN },
      { label: "普通用户", value: TargetAudience.USER }
    ];
  }

  /** 获取批量操作选项 */
  static getBatchOperationOptions() {
    return [
      { label: "发布", value: BatchOperationType.PUBLISH },
      { label: "存档", value: BatchOperationType.ARCHIVE },
      { label: "删除", value: BatchOperationType.DELETE },
      { label: "置顶", value: BatchOperationType.TOP },
      { label: "取消置顶", value: BatchOperationType.UNTOP },
      { label: "设为弹窗", value: BatchOperationType.POPUP },
      { label: "取消弹窗", value: BatchOperationType.UNPOPUP }
    ];
  }

  /** 检查公告是否即将过期 */
  static isExpiringSoon(expireTime: string, days: number = 3): boolean {
    const expire = new Date(expireTime);
    const now = new Date();
    const diffTime = expire.getTime() - now.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays <= days && diffDays > 0;
  }

  /** 计算剩余天数 */
  static calculateRemainingDays(expireTime: string): number {
    const expire = new Date(expireTime);
    const now = new Date();
    const diffTime = expire.getTime() - now.getTime();
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  }
}
